'use strict';

/* 
@see: https://www.briankeating.net/post/Angularjs-NET-File-Upload 
@seealso:https://github.com/danialfarid/ng-file-upload
@seealso: https://github.com/johnpapa/angular-styleguide
*/

var app = angular.module('oplacoSampleApp.controllers', []);

app.controller('FileUploadCtrl', ['$upload', 'oplacoSettings', function ($upload, oplacoSettings) {
        
    var vm = this;
    vm.webapi = oplacoSettings.apiServiceBaseUri + "/Api/Upload";
    vm.upload = [];    
    vm.thumbnails = [];
    vm.progress = 0;
    vm.error = "";

    vm.onFileSelect = function ($files) {
        //$files: an array of files selected, each file has name, size, and type.
        for (var i = 0; i < $files.length; i++) {
            var $file = $files[i];
            (function (index) {
                vm.upload[index] = $upload.upload({
                    url: vm.webapi, 
                    method: "POST",                    
                    file: $file
                }).progress(function (evt) {
                    // get upload percentage
                    vm.progress = parseInt(100.0 * evt.loaded / evt.total);
                }).success(function (data, status, headers, config) {
                    vm.thumbnails = data;
                    // file is uploaded successfully
                    console.log(data);
                }).error(function (data, status, headers, config) {
                    // file failed to upload
                    vm.error = data;
                });
            })(i);
        }
    }

    vm.abortUpload = function (index) {
        vm.upload[index].abort();
    }
        
}]);
